<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>编辑</h3>
      <el-form ref="ioralStock" :rules="rules" :model="ioralStock" label-width="150px">
        <el-form-item label="产品批号" prop="batchNumber">
          <el-select v-model="ioralStock.batchNumber" placeholder="请选择产品批号">
            <el-option
              v-for="(value, key) in batchNumbers"
              :key="key"
              :label="value"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="收货单位" prop="userName">
          <el-input v-model="ioralStock.userName"/>
        </el-form-item>-->
        <el-form-item label="发货方式" prop="deliveryType">
          <el-input v-model="ioralStock.deliveryType"/>
        </el-form-item>
        <el-form-item label="使用时间" prop="useTime">
          <el-input v-model="ioralStock.useTime">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="件数" prop="pieces">
          <el-input v-model="ioralStock.pieces" @blur="getAllinfo"/>
        </el-form-item>
        <el-form-item label="订量" prop="orderCount">
          <el-input v-model="ioralStock.orderCount" @blur="getAllinfo"/>
        </el-form-item>
        <el-form-item label="分装体积" prop="volume">
          <el-input v-model="ioralStock.volume" readonly/>
        </el-form-item>
        <el-form-item label="分装活度" prop="activity">
          <el-input v-model="ioralStock.activity" readonly/>
        </el-form-item>

      </el-form>
    </el-card>
    <el-card class="box-card">
      <!--<div v-for="o in 4" :key="o" class="text item">
        '' {{'列表内容 ' + o }}
      </div>-->
      <el-table  size="small" :data="productInfo"
                 :header-cell-style="{fontSize: '16px', backgroundColor: '#ffff66',color:'#333'}">
        <el-table-column align="center" min-width="60" label="生产日期" prop="date"/>
        <el-table-column align="center" min-width="80" label="产品总活度(Ci)" prop="totalActivity"/>
        <el-table-column align="center" min-width="90" label="产品总体积(ml)" prop="totalVolume"/>
        <el-table-column align="center" min-width="90" label="此次备货活度(Ci)" prop="actualCount"/>
        <el-table-column align="center" min-width="90" label="此次备货体积(ml)" prop="volume"/>
        <el-table-column align="center" min-width="80" label="剩余体积(ml)" prop="remainVolume"/>
        <el-table-column align="center" min-width="80" label="剩余活度(Ci)" prop="remainActivity"/>
      </el-table>

    </el-card>


    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新</el-button>
    </div>
  </div>
</template>

<style>
  .el-card {
    margin-bottom: 10px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
  // eslint-disable-next-line no-unused-vars
  import { detailiorderStock, editiorderStock } from '@/api/business/iorderStock'
  import { listBachNumbers,getInfoByOrderCount} from '@/api/business/productProduction'
  import { createStorage, uploadPath } from '@/api/business/storage'
  import Editor from '@tinymce/tinymce-vue'
  import { MessageBox } from 'element-ui'
  import { getToken } from '@/utils/auth'

  export default {
    name: 'iorderStockedit',
    components: { Editor },
    data() {
      return {
        uploadPath,
        newKeywordVisible: false,
        newKeyword: '',
        keywords: [],
        productInfo:[],
        galleryFileList: [],
        batchNumbers: [],
        extraParam: {
          batchNumber: '',
          activity: '',
        },
        ioralStock: [],
        listQuery: { batchNumber: '', orderCount: '', useTime: '',piece:0},
        specVisiable: false,
        specForm: { specification: '', value: '', picUrl: '' },
        specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
        mods: [
          { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
        ],
        /* attributeVisiable: false,*/
        /* attributeForm: { attribute: '', value: '' },
        attributes: [],*/
        rules: {
          batchNumber: [
            { required: true, message: '产品批号不能为空', trigger: 'blur' }
          ],
          volume: [{ required: true, message: '分装体积不能为空', trigger: 'blur' }]
        },
        editorInit: {
          language: 'zh_CN',
          convert_urls: false,
          plugins: [
            'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
          ],
          toolbar: [
            'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
            'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
          ],
          images_upload_handler: function(blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('file', blobInfo.blob())
            createStorage(formData)
              .then(res => {
                success(res.data.data.url)
              })
              .catch(() => {
                failure('上传失败，请重新上传')
              })
          }
        }
      }
    },
    computed: {
      headers() {
        return {
          'X-Dts-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.init()
      this.getBatchNumbers()
    },
    methods: {
      init: function() {
        if (this.$route.query.id == null) {
          return
        }

        const iorderStockId = this.$route.query.id
        detailiorderStock(iorderStockId).then(response => {
          this.ioralStock = response.data.data.ioralStock
          /* this.specifications = response.data.data.specifications*/
          /* for (var i = 0; i < this.iorderStock.gallery.length; i++) {
            this.galleryFileList.push({
              url: this.iorderStock.gallery[i]
            })
          }*/
          /*const keywords = response.data.data.ioralStock.keywords
          if (keywords !== null) {
            this.keywords = keywords.split(',')
          }*/
        })

        /* listCatAndBrand().then(response => {
          this.categoryList = response.data.data.categoryList
          this.brandList = response.data.data.brandList
        })*/
      },
      /* handleCategoryChange(value) {
        this.iorderStock.categoryId = value[value.length - 1]
      },*/
      getBatchNumbers() {
        listBachNumbers(this.query).then(response => {
          this.batchNumbers = response.data.data.batchNumbers/*.sort((a, b) => new Date(a) - new Date(b))*/
          /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
        }).catch(() => {
          console.log('getList catch')
          /*this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*/
        })

      },
      getAllinfo(){
        this.listQuery.batchNumber=this.ioralStock.batchNumber
        this.listQuery.orderCount=this.ioralStock.orderCount
        this.listQuery.useTime=this.ioralStock.useTime
        this.listQuery.piece=this.ioralStock.pieces
        getInfoByOrderCount(this.listQuery).then(response=>{
          this.productInfo=response.data.data.productInfo

          /* if(response.data.data.remainActivity<=0){
             MessageBox.alert('剩余体积（活度）不足：' + response.data.data.remainActivity, '警告', {
               confirmButtonText: '确定',
               type: 'error'
             })
           }*/
        }).catch(() => {
          console.log('业务错误')
          /*this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*/
        })
      },
      handleCancel: function() {
        this.$router.push({ path: '/iorders/list4' })
      },
      handleEdit: function() {
        const finaliorderStock = {
          ioralStock: this.ioralStock
          /* specifications: this.specifications,
          products: this.products,
          attributes: this.attributes*/
        }
        editiorderStock(finaliorderStock)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '更新成功'
            })
            this.$router.push({ path: '/iorders/list4' })
          })
          .catch(response => {
            MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
              confirmButtonText: '确定',
              type: 'error'
            })
          })
      },
      handleClose(tag) {
        this.keywords.splice(this.keywords.indexOf(tag), 1)
        this.iorderStock.keywords = this.keywords.toString()
      },
      showInput() {
        this.newKeywordVisible = true
        this.$nextTick(_ => {
          this.$refs.newKeywordInput.$refs.input.focus()
        })
      },
      handleInputConfirm() {
        const newKeyword = this.newKeyword
        if (newKeyword) {
          this.keywords.push(newKeyword)
          this.iorderStock.keywords = this.keywords.toString()
        }
        this.newKeywordVisible = false
        this.newKeyword = ''
      },
      uploadPicUrl: function(response) {
        this.iorderStock.picUrl = response.data.url
      },
      uploadOverrun: function() {
        this.$message({
          type: 'error',
          message: '上传器材个数超出限制!最多上传5张图片!'
        })
      },
      handleGalleryUrl(response, file, fileList) {
        if (response.errno === 0) {
          this.iorderStock.gallery.push(response.data.url)
        }
      },
      handleRemove: function(file, fileList) {
        for (var i = 0; i < this.iorderStock.gallery.length; i++) {
          // 这里存在两种情况
          // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
          //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
          // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
          var url
          if (file.response === undefined) {
            url = file.url
          } else {
            url = file.response.data.url
          }

          if (this.iorderStock.gallery[i] === url) {
            this.iorderStock.gallery.splice(i, 1)
          }
        }
      },
      specChanged: function(label) {
        if (label === false) {
          this.specifications = [
            { specification: '规格', value: '标准', picUrl: '' }
          ]
          this.products = [
            { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
          ]
        } else {
          this.specifications = []
          this.products = []
        }
      },
      uploadSpecPicUrl: function(response) {
        this.specForm.picUrl = response.data.url
      },
      handleSpecificationShow() {
        this.specForm = { specification: '', value: '', picUrl: '' }
        this.specVisiable = true
      },
      handleSpecificationAdd() {
        var index = this.specifications.length - 1
        for (var i = 0; i < this.specifications.length; i++) {
          const v = this.specifications[i]
          if (v.specification === this.specForm.specification) {
            index = i
          }
        }

        this.specifications.splice(index + 1, 0, this.specForm)
        this.specVisiable = false

        this.specToProduct()
      },
      handleSpecificationDelete(row) {
        const index = this.specifications.indexOf(row)
        this.specifications.splice(index, 1)
        this.specToProduct()
      },
      specToProduct() {
        if (this.specifications.length === 0) {
          return
        }
        // 根据specifications创建临时规格列表
        var specValues = []
        var spec = this.specifications[0].specification
        var values = []
        values.push(0)

        for (var i = 1; i < this.specifications.length; i++) {
          const aspec = this.specifications[i].specification

          if (aspec === spec) {
            values.push(i)
          } else {
            specValues.push(values)
            spec = aspec
            values = []
            values.push(i)
          }
        }
        specValues.push(values)

        // 根据临时规格列表生产货品规格
        // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
        var productsIndex = 0
        var products = []
        var combination = []
        var n = specValues.length
        for (var s = 0; s < n; s++) {
          combination[s] = 0
        }
        var index = 0
        var isContinue = false
        do {
          var specifications = []
          for (var x = 0; x < n; x++) {
            var z = specValues[x][combination[x]]
            specifications.push(this.specifications[z].value)
          }
          products[productsIndex] = {
            id: productsIndex,
            specifications: specifications,
            price: 0.0,
            number: 0,
            url: ''
          }
          productsIndex++

          index++
          combination[n - 1] = index
          for (var j = n - 1; j >= 0; j--) {
            if (combination[j] >= specValues[j].length) {
              combination[j] = 0
              index = 0
              if (j - 1 >= 0) {
                combination[j - 1] = combination[j - 1] + 1
              }
            }
          }
          isContinue = false
          for (var p = 0; p < n; p++) {
            if (combination[p] !== 0) {
              isContinue = true
            }
          }
        } while (isContinue)

        this.products = products
      },
      handleProductShow(row) {
        this.productForm = Object.assign({}, row)
        this.productVisiable = true
      },
      uploadProductUrl: function(response) {
        this.productForm.url = response.data.url
      },
      handleProductEdit() {
        for (var i = 0; i < this.products.length; i++) {
          const v = this.products[i]
          if (v.id === this.productForm.id) {
            this.products.splice(i, 1, this.productForm)
            break
          }
        }
        this.productVisiable = false
      },
      handleAttributeShow() {
        this.attributeForm = {}
        this.attributeVisiable = true
      },
      handleAttributeAdd() {
        this.attributes.unshift(this.attributeForm)
        this.attributeVisiable = false
      },
      handleAttributeDelete(row) {
        const index = this.attributes.indexOf(row)
        this.attributes.splice(index, 1)
      }
    }
  }
</script>
